package cn.geapi.filter.aop;

import java.lang.annotation.Annotation;

import org.apache.log4j.Logger;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;

import cn.geapi.core.util.security.HashIdContext;
import cn.geapi.core.util.security.annotation.Hashable;

public class HashIdWebArgumentResolver implements WebArgumentResolver {
	private final static Logger LOGGER = Logger
			.getLogger(WebArgumentResolver.class);

	private boolean isIDNumber(String str) {
		return str.matches("\\d+");
	}

	public Object resolveArgument(MethodParameter methodParameter,
			NativeWebRequest webRequest) throws Exception {
		Annotation[][] annotations = methodParameter.getMethod()
				.getParameterAnnotations();
		Hashable ann = null;
		int idx = methodParameter.getParameterIndex();
		if (annotations.length > idx) {
			Annotation[] ans = annotations[idx];
			for (Annotation an : ans) {
				if (an.annotationType().isAssignableFrom(Hashable.class)) {
					ann = (Hashable) an;
					break;
				}
			}
		}

		if (null != ann) {
			String valueStr = webRequest.getParameter(ann.name());
			if (valueStr == null) {
				LOGGER.info(ann.name()
						+ " is null,colud not converted to long");
				return null;
			}

			else if (valueStr.length() < 8 && isIDNumber(valueStr)) {
				LOGGER.info("receive not encoded art id [" + valueStr + "]");
				return Long.parseLong(valueStr);
			} else {
				return HashIdContext.getHashIdStrategy(ann.idType()).decrypt(
						valueStr);
			}
		}
		return WebArgumentResolver.UNRESOLVED;
	}
}
